package com.czl.websocket.server;

import com.czl.websocket.type.MessageType;

import java.util.*;

public class ChatMatchService {

    //匹配周期 毫秒
    static final int mathCycle = 1*1000;

     private static Set<String> readyList=Collections.synchronizedSet(new HashSet<String>());

         public static void start(String uid){
             readyList.add(uid);
         }

         public static void stop(String uid){
             readyList.remove(uid);
         }

        public static synchronized String[] match(){
             String[] strss= new String[2];
            if(readyList.size()>=2){
                Iterator<String> iterator = readyList.iterator();
                if(iterator.hasNext()){
                    String next = iterator.next();
                    strss[0]=next;
                    iterator.remove();
                }
                if(iterator.hasNext()){
                    String next = iterator.next();
                    strss[1]=next;
                    iterator.remove();
                }
                WebSockeManger.send("1",strss[0], MessageType.Math,strss[1]);
                WebSockeManger.send("1",strss[1],MessageType.Math,strss[0]);
            }

            return strss;
        }


    /**
     * 根据心跳判断存活状态客户端 移除非存活客户端连接
     */
    public static void mathTask(){
        System.out.println("自动匹配开始");
        while(true){
            try {
                System.out.println("自动匹配中。。。。。");
                match();
                Thread.sleep(mathCycle);
            } catch (InterruptedException e) {
                e.printStackTrace();
                System.out.println("自动匹配系统发生异常");
            }
        }



    }
}
